package io.jee.runshan.controller.web;

import io.jee.medusa.orm.condition.Condition;
import io.jee.medusa.orm.condition.ConditionGroup;
import io.jee.medusa.vo.ResultBean;
import io.jee.runshan.domain.OrderContact;
import io.jee.runshan.domain.PreSaleOrder;
import io.jee.runshan.domain.PreSaleOrderProduct;
import io.jee.runshan.domain.Product;
import io.jee.runshan.domain.ShoppingCar;
import io.jee.runshan.domain.ShoppingCarProduct;
import io.jee.runshan.service.IOrderContactService;
import io.jee.runshan.service.IPreSaleOrderProductService;
import io.jee.runshan.service.IPreSaleOrderService;
import io.jee.runshan.service.IProductService;
import io.jee.runshan.service.IShoppingCarProductService;
import io.jee.runshan.service.IShoppingCarService;
import io.jee.runshan.utils.JsonUtil;
import io.jee.runshan.utils.WeixinUtils;
import io.jee.runshan.vo.GoodsTransfer;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeansException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/web/preSaleOrder/")
@SuppressWarnings("unchecked")
public class WebPreSaleOrderController {
	@Resource
	private IShoppingCarProductService carProductService;
	@Resource
	private IShoppingCarService carService;
	@Resource
	private IPreSaleOrderService orderService;
	@Resource
	private IOrderContactService contactService; 
	@Resource
	private IProductService productService;
	@Resource 
	private IPreSaleOrderProductService orderProductService;
	
	/**
	 * 订单确认页面
	 * @author ynshun
	 * @param request
	 * @return
	 */
	@RequestMapping("detail")
	public ModelAndView detail(HttpServletRequest request, String goods) {
		List<ShoppingCarProduct> products = new ArrayList<ShoppingCarProduct>();
		ShoppingCar car = null;
		OrderContact constact = null;
		try {
			String wxOpenid = WeixinUtils.getOpenid(request);
			List<GoodsTransfer> list = JsonUtil.jsonToList(goods, GoodsTransfer.class);
			for (GoodsTransfer gds : list) {
				Product product = productService.get(gds.getId());
				ShoppingCarProduct carProduct = new ShoppingCarProduct();
				carProduct.setBuyCount(gds.getCount());
				carProduct.setBuyPrice(product.getSalesPrice());
				carProduct.setProduct(product);
				products.add(carProduct);
			}
			
			constact = contactService.unique("wxOpenid", wxOpenid);
			car = new ShoppingCar();
			for (ShoppingCarProduct product : products) {
				car.addPrudoct(product);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ModelAndView("/web/weixin/preSaleOrder/detail")
		.addObject("products", products)
		.addObject("car", car)
		.addObject("constact", constact);
	}
	
	/**
	 * 查看所有订单列表
	 * @author ynshun
	 * @param request
	 * @return
	 */
	@RequestMapping("list")
	public ModelAndView list(HttpServletRequest request) {
		List<PreSaleOrder> orders = null;
		try {
			String wxOpenid = WeixinUtils.getOpenid(request);
			ConditionGroup group = new ConditionGroup();
			group.and(Condition.onNumber("wxOpenid").eq(wxOpenid));
			group.and(Condition.onBool("showed").eq(true));
			orders = orderService.list(group);
			for (PreSaleOrder order : orders) {
				List<PreSaleOrderProduct> products = orderProductService.list("order.id", order.getId());
				for (PreSaleOrderProduct product : products) {
					order.addProduct(product);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ModelAndView("/web/weixin/preSaleOrder/list").addObject("orders", orders);
	}
	
	/**
	 * 从购物车中选商品购买
	 * @author ynshun
	 * @param request
	 * @param name
	 * @param mobile
	 * @param memo
	 * @param alipayAccount
	 * @param goods
	 * @return
	 */
	@RequestMapping(value = "save")
	public ModelAndView save(HttpServletRequest request, String name, String mobile, String memo, String alipayAccount, String goods ) {
		ResultBean<?> resultBean = null;
		try {
			String wxOpenid = WeixinUtils.getOpenid(request);
			resultBean = orderService.doneOrder(false, wxOpenid, name, mobile, memo, alipayAccount, goods);
			
			if (!resultBean.success()) {
				OrderContact constact = contactService.unique("wxOpenid", wxOpenid);
				List<ShoppingCarProduct> products = (List<ShoppingCarProduct>) resultBean.getData();
				ShoppingCar car = new ShoppingCar();
				for (ShoppingCarProduct product : products) {
					car.addPrudoct(product);
				}
				
				return new ModelAndView("/web/weixin/preSaleOrder/detail")
				.addObject("products", products)
				.addObject("car", car)
				.addObject("success", resultBean.success())
				.addObject("message", resultBean.getMessage())
				.addObject("constact", constact);
			}
		} catch (BeansException e) {
			e.printStackTrace();
		}
		return new ModelAndView("/web/weixin/preSaleOrder/submitSuccess").addObject("order", resultBean.getData());
	}
	
	/**
	 * 单个商品直接下单
	 * @author ynshun
	 * @param request
	 * @param name
	 * @param mobile
	 * @param memo
	 * @param alipayAccount
	 * @param goods
	 * @return
	 */
	@RequestMapping(value = "onceSave", produces = { "application/json" })
	public ModelAndView onceSave(HttpServletRequest request, String name, String mobile, String memo, String alipayAccount, String goods ) {
		ResultBean<?> resultBean = null;
		try {
			String wxOpenid = WeixinUtils.getOpenid(request);
			resultBean = orderService.doneOrder(true, wxOpenid, name, mobile, memo, alipayAccount, goods);
			
			if (!resultBean.success()) {
				OrderContact constact = contactService.unique("wxOpenid", wxOpenid);
				List<ShoppingCarProduct> products = (List<ShoppingCarProduct>) resultBean.getData();
				ShoppingCar car = new ShoppingCar();
				for (ShoppingCarProduct product : products) {
					car.addPrudoct(product);
				}
				
				return new ModelAndView("/web/weixin/preSaleOrder/detail")
				.addObject("products", products)
				.addObject("car", car)
				.addObject("success", resultBean.success())
				.addObject("message", resultBean.getMessage())
				.addObject("constact", constact);
			}
		} catch (BeansException e) {
			e.printStackTrace();
		}
		return new ModelAndView("/web/weixin/preSaleOrder/submitSuccess").addObject("order", resultBean.getData());
	}
	
	/**
	 * 用户退订订单
	 * @param request
	 * @param orderId
	 * @return
	 */
	@RequestMapping(value = "unsubscribe", produces = { "application/json" })
	@ResponseBody
	public ResultBean<?> unsubscribe(HttpServletRequest request, Integer orderId ) {
		try {
			String wxOpenid = WeixinUtils.getOpenid(request);
			PreSaleOrder order = orderService.get(orderId);
			if (order == null || !order.getWxOpenid().equals(wxOpenid)) {
				return ResultBean.result(false, "操作异常，请自重！");
			}
			orderService.unsubscribe(order);
		} catch (BeansException e) {
			e.printStackTrace();
		}
		return ResultBean.result(true, "退订成功");
	}
	
	/**
	 * 用户删除订单
	 * @param request
	 * @param orderId
	 * @return
	 */
	@RequestMapping(value = "delete", produces = { "application/json" })
	@ResponseBody
	public ResultBean<?> delete(HttpServletRequest request, Integer orderId ) {
		try {
			String wxOpenid = WeixinUtils.getOpenid(request);
			PreSaleOrder order = orderService.get(orderId);
			if (order == null || !order.getWxOpenid().equals(wxOpenid)) {
				return ResultBean.result(false, "操作异常，请自重！");
			}
			order.setShowed(false);
			orderService.update(order);
		} catch (BeansException e) {
			e.printStackTrace();
		}
		return ResultBean.result(true, "删除成功");
	}

}
